﻿using System.Text;
namespace il2lua.Services;

public class NameService : INameService
{
    private readonly Stack<StringBuilder> _nameBuilders = new();
        
    private StringBuilder PopNameBuilder()
    {
        return _nameBuilders.Count > 0 ? _nameBuilders.Pop() : new StringBuilder();
    }
        
    private string PushNameBuilder(StringBuilder builder)
    {
        var text = builder.ToString();
        builder.Clear();
        _nameBuilders.Push(builder);
        return text;
    }
    public string GetName(string name)
    {
        var builder = PopNameBuilder();
        if (name == ".ctor")
            return "__ctor__";
        foreach (var ch in name)
        {
            switch (ch)
            {
                case '`':
                case '<':
                case '>':
                    builder.Append('_');
                    break;
                default:
                    builder.Append(ch);
                    break;
            }
        }
        return PushNameBuilder(builder);
    }
}